﻿using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Wordprocessing;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.FrameOrder.Dto;
using NP.BPMReportPlatform.HR.Dto;
using NP.BPMReportPlatform.RecurringJobs;
using NP.BPMReportPlatform.TaxManage.Dto;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.ObjectMapping;

namespace NP.BPMReportPlatform.TaxManage
{

    public class NotesRedLetterService : BPMReportPlatformAppService, INotesRedLetterService
    {
        private readonly SqlSugarClient _dbBusiness;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        public NotesRedLetterService(ISqlSugarAppService sqlSugarAppService
            , IBPMPlatformAppService iBPMPlatformApp
            , IBPMUtilsAppService bPMUtilsApp)
        {
            _dbBusiness = sqlSugarAppService.GetBusinessInstance();
            _iBPMPlatformApp = iBPMPlatformApp;
            _bPMUtilsApp = bPMUtilsApp;

        }

        public async Task<List<NotesRedLetterDto>> ExportAsync(NotesRedLetterSearchDto input)
        {
            return await _getAll(input).ToListAsync();
        }

        public async Task<PagedResultDto<NotesRedLetterDto>> GetAllAsync(NotesRedLetterSearchDto input)
        {
            RefAsync<int> totalCount = 0;
            var result = new PagedResultDto<NotesRedLetterDto>();
            try
            {
                //var A = _dbBusiness.Queryable<NotesRedLetterApplyMain, NotesRedLetterApplyTableMain>((a, b) => new JoinQueryInfos(JoinType.Inner, a.InstanceNumber == b.InstanceNumber)).ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

                if (input.flowstate != null)
                {
                    if (input.flowstate.Contains("Processing"))
                    {
                        input.flowstate.Add("审批中");
                    }
                } 

                var getQuery = _getAll(input);
                var mapperList = await getQuery.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

                AssignList(mapperList);
                result.TotalCount = totalCount;
                result.Items = mapperList;
            }
            catch (Exception EX)
            {

                throw;
            }

            return result;
        }

        private ISugarQueryable<NotesRedLetterDto> _getAll(NotesRedLetterSearchDto input)
        {

            var result = _dbBusiness.Queryable<NotesRedLetterApplyMain, NotesRedLetterApplyTableMain>((a, b) => new JoinQueryInfos(JoinType.Inner, a.InstanceNumber == b.InstanceNumber))
                .WhereIF(!string.IsNullOrEmpty(input.InstanceNumber), (a, b) => a.InstanceNumber.Contains(input.InstanceNumber))
                .WhereIF(!string.IsNullOrEmpty(input.companyCode), (a, b) => a.companyCode.Contains(input.companyCode))
                 .WhereIF(!string.IsNullOrEmpty(input.memoReason), (a, b) => a.memoReason.Contains(input.memoReason))
                  .WhereIF(!string.IsNullOrEmpty(input.sellerCode), (a, b) => b.sellerCode.Contains(input.sellerCode))
                   .WhereIF(!string.IsNullOrEmpty(input.customVourcherNo), (a, b) => b.customVourcherNo.Contains(input.customVourcherNo))
                    .WhereIF(!string.IsNullOrEmpty(input.redLetterNumber), (a, b) => b.redLetterNumber.Contains(input.redLetterNumber))
                    .WhereIF(input.beginTime.HasValue && input.endTime.HasValue, (a, b) => a.AddTime > input.beginTime && a.AddTime < input.endTime)
                    .WhereIF(input.flowstate != null && input.flowstate.Count> 0,(a,b) => SqlFunc.ContainsArray<string>(input.flowstate.ToArray(),  a.FlowState))
                    .Select((a, b) => new NotesRedLetterDto()
                    {
                        flowstate = a.FlowState,
                        InstanceNumber = a.InstanceNumber,
                        UserName = a.UserName,
                        UserCode = a.UserCode,
                        memoReason = a.memoReason,
                        companyCode = a.companyCode,
                        companyName = a.companyName,
                        companyTaxNo = a.companyTaxNo,
                        chcCompanyStatus = a.chcCompanyStatus == "0" ? "关企" : "供应商",
                        remark = a.remark,
                        sellerCode = b.sellerCode,
                        sellerName = b.sellerName,
                        sellerNameNumber = b.sellerNameNumber,
                        invoiceNumber = b.invoiceNumber,
                        invoiceCode = b.invoiceCode,
                        invoiceTypeName = b.invoiceTypeName,
                        redLetterType = b.redLetterType,
                        accountType = b.accountType,
                        amountWithTax = b.amountWithTax,
                        amountWithOutTax = b.amountWithOutTax,
                        tax = b.tax,
                        list45 = b.list45,
                        list28 = b.list28,
                        list92 = b.list92,
                        deviceSelectValue = b.deviceSelectValue,
                        redLetterNumber = b.redLetterNumber,
                        applyStatusText = b.applyStatusText,
                        customVourcherNo = b.customVourcherNo,
                        newRedInvoiceNumber = b.newRedInvoiceNumber,
                    }).OrderBy(a => a.InstanceNumber, OrderByType.Desc);

            return result;
        }

        private async Task<List<NotesRedLetterDto>> AssignList(List<NotesRedLetterDto> listViewDto)
        {

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);
                x.flowstateName = getName(x.flowstate);
            } 
            );
            return listViewDto;
        }

        private  string getName(string flowstate)
        {
           flowstate= flowstate.ToLower();
            if (flowstate== "approved")
            {
                return "审批通过";
              }
            if (flowstate == "rejected")
            {
                return "已退回";
              }
            if (flowstate == "canceled")
            {
                return "审批终止";
              }
            if (flowstate == "refused")
            {
                return "审批拒绝";
              }
            return "待审批";
        }




    }
}
